package com.example.musicplayer.adapter

import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.musicplayer.fragment.MusicPlayerFragment
import com.example.musicplayer.fragment.MusicRecommendationFragment
import com.example.musicplayer.fragment.PlaylistFragment
import com.example.musicplayer.model.Banner
import com.example.musicplayer.model.Music
import com.example.musicplayer.model.RecommendMusic
import java.lang.ref.WeakReference

/**
 * Tab的适配器
 */
class TabAdapter(
    fragmentActivity: AppCompatActivity, private val bannerList: List<Banner>,
    private val musicTitleTextView: TextView, private val musicSingerTextView: TextView,
    private val musicCoverImageView: ImageView, private val playPauseButton: ImageView,
    private val musicList: List<Music>, private val recommendMusicList: List<RecommendMusic>
) : FragmentStateAdapter(fragmentActivity) {

    companion object {
        var musicPlayerFragment: WeakReference<MusicPlayerFragment>? = null
    }

    init {
        val fragment = MusicPlayerFragment()
        musicPlayerFragment = WeakReference(fragment)
    }

    private val playlistFragment = PlaylistFragment(
        musicTitleTextView,
        musicSingerTextView,
        musicCoverImageView,
        playPauseButton,
        musicList,
        musicPlayerFragment?.get() ?: MusicPlayerFragment() // 确保不为null
    )

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            1 -> {
                val fragment = musicPlayerFragment?.get()
                if (fragment == null) {
                    val newFragment = MusicPlayerFragment()
                    musicPlayerFragment = WeakReference(newFragment)
                    newFragment
                } else {
                    fragment
                }
            }
            2 -> playlistFragment
            else -> MusicRecommendationFragment(bannerList, recommendMusicList)
        }
    }

    fun getPlaylistFragment(): PlaylistFragment {
        return playlistFragment
    }

    override fun getItemCount(): Int {
        return 3
    }
}